#include "AlarmModel.h"
#include "services/DatabaseService.h"
#include "utils/Logger.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

AlarmModel::AlarmModel(QObject *parent)
    : QAbstractListModel(parent),
      m_showOnlyUnacknowledged(false)
{
}

AlarmModel::~AlarmModel()
{
}

// 返回行数
int AlarmModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_alarms.count();
}

// 返回数据
QVariant AlarmModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_alarms.count())
        return QVariant();

    const AlarmRecord &alarm = m_alarms.at(index.row());

    switch (role)
    {
    case IdRole:
        return alarm.id();
    case DeviceIdRole:
        return alarm.deviceId();
    case TimestampRole:
        return alarm.timestamp().toString("yyyy-MM-dd HH:mm:ss");
    case AlarmTypeRole:
        return alarm.alarmTypeString();
    case AlarmLevelRole:
        return alarm.alarmLevelString();
    case ParamNameRole:
        return alarm.paramName();
    case ParamValueRole:
        return alarm.paramValue();
    case ThresholdRole:
        return alarm.threshold();
    case DescriptionRole:
        return alarm.description();
    case AcknowledgedRole:
        return alarm.isAcknowledged();
    case AcknowledgedByRole:
        return alarm.acknowledgedBy();
    case AcknowledgedAtRole:
        return alarm.acknowledgedAt().toString("yyyy-MM-dd HH:mm:ss");
    default:
        return QVariant();
    }
}

// 角色名称映射（QML 中使用）
QHash<int, QByteArray> AlarmModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[IdRole] = "alarmId";
    roles[DeviceIdRole] = "deviceId";
    roles[TimestampRole] = "timestamp";
    roles[AlarmTypeRole] = "alarmType";
    roles[AlarmLevelRole] = "alarmLevel";
    roles[ParamNameRole] = "paramName";
    roles[ParamValueRole] = "paramValue";
    roles[ThresholdRole] = "threshold";
    roles[DescriptionRole] = "description";
    roles[AcknowledgedRole] = "acknowledged";
    roles[AcknowledgedByRole] = "acknowledgedBy";
    roles[AcknowledgedAtRole] = "acknowledgedAt";
    return roles;
}

// 获取未确认报警数量
int AlarmModel::unacknowledgedCount() const
{
    int count = 0;
    for (const AlarmRecord &alarm : m_alarms)
    {
        if (!alarm.isAcknowledged())
            count++;
    }
    return count;
}

// 设置设备ID过滤
void AlarmModel::setDeviceIdFilter(const QString &deviceId)
{
    if (m_deviceIdFilter == deviceId)
        return;

    m_deviceIdFilter = deviceId;
    emit deviceIdFilterChanged();

    qDebug() << "AlarmModel: 设置设备过滤:" << deviceId;
}

// 设置报警级别过滤
void AlarmModel::setLevelFilter(const QString &level)
{
    if (m_levelFilter == level)
        return;

    m_levelFilter = level;
    emit levelFilterChanged();

    qDebug() << "AlarmModel: 设置级别过滤:" << level;
}

// 设置仅显示未确认报警
void AlarmModel::setShowOnlyUnacknowledged(bool show)
{
    if (m_showOnlyUnacknowledged == show)
        return;

    m_showOnlyUnacknowledged = show;
    emit showOnlyUnacknowledgedChanged();

    qDebug() << "AlarmModel: 仅显示未确认报警:" << show;
}

// 从数据库加载报警记录
bool AlarmModel::loadFromDatabase()
{
    qInfo() << "AlarmModel: 从数据库加载报警记录";

    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    QString sql = QString("SELECT id, device_id, timestamp, alarm_type, alarm_level, "
                          "param_name, param_value, threshold, description, "
                          "acknowledged, acknowledged_by, acknowledged_at "
                          "FROM alarm_records WHERE %1 ORDER BY timestamp DESC")
                      .arg(buildWhereClause());

    if (!query.exec(sql))
    {
        qWarning() << "AlarmModel: 查询失败:" << query.lastError().text();
        return false;
    }

    // 清空现有数据
    beginResetModel();
    m_alarms.clear();

    // 加载数据
    while (query.next())
    {
        AlarmRecord alarm;
        alarm.setId(query.value(0).toInt());
        alarm.setDeviceId(query.value(1).toString());
        alarm.setTimestamp(query.value(2).toDateTime());
        alarm.setAlarmType(AlarmRecord::stringToAlarmType(query.value(3).toString()));
        alarm.setAlarmLevel(AlarmRecord::stringToAlarmLevel(query.value(4).toString()));
        alarm.setParamName(query.value(5).toString());
        alarm.setParamValue(query.value(6).toDouble());
        alarm.setThreshold(query.value(7).toDouble());
        alarm.setDescription(query.value(8).toString());
        alarm.setAcknowledged(query.value(9).toBool());
        alarm.setAcknowledgedBy(query.value(10).toString());
        alarm.setAcknowledgedAt(query.value(11).toDateTime());

        m_alarms.append(alarm);
    }

    endResetModel();
    emit countChanged();
    emit unacknowledgedCountChanged();

    qInfo() << "AlarmModel: 加载完成，共" << m_alarms.count() << "条报警记录";
    return true;
}

// 加载最近 N 小时的报警
bool AlarmModel::loadRecentAlarms(int hours)
{
    QDateTime endTime = QDateTime::currentDateTime();
    QDateTime startTime = endTime.addSecs(-hours * 3600);
    return loadAlarmsDateRange(startTime, endTime);
}

// 加载未确认的报警
bool AlarmModel::loadUnacknowledgedAlarms()
{
    m_showOnlyUnacknowledged = true;
    emit showOnlyUnacknowledgedChanged();
    return loadFromDatabase();
}

// 加载指定设备的报警
bool AlarmModel::loadAlarmsForDevice(const QString &deviceId)
{
    m_deviceIdFilter = deviceId;
    emit deviceIdFilterChanged();
    return loadFromDatabase();
}

// 加载指定级别的报警
bool AlarmModel::loadAlarmsByLevel(const QString &level)
{
    m_levelFilter = level;
    emit levelFilterChanged();
    return loadFromDatabase();
}

// 加载日期范围内的报警
bool AlarmModel::loadAlarmsDateRange(const QDateTime &start, const QDateTime &end)
{
    qInfo() << "AlarmModel: 查询日期范围 -"
            << "从" << start.toString("yyyy-MM-dd HH:mm:ss")
            << "到" << end.toString("yyyy-MM-dd HH:mm:ss");

    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    QString whereClause = buildWhereClause();
    if (!whereClause.isEmpty() && whereClause != "1=1")
    {
        whereClause += " AND ";
    }
    whereClause += QString("timestamp >= '%1' AND timestamp <= '%2'")
                       .arg(start.toString("yyyy-MM-dd HH:mm:ss"))
                       .arg(end.toString("yyyy-MM-dd HH:mm:ss"));

    QString sql = QString("SELECT id, device_id, timestamp, alarm_type, alarm_level, "
                          "param_name, param_value, threshold, description, "
                          "acknowledged, acknowledged_by, acknowledged_at "
                          "FROM alarm_records WHERE %1 ORDER BY timestamp DESC")
                      .arg(whereClause);

    if (!query.exec(sql))
    {
        qWarning() << "AlarmModel: 查询失败:" << query.lastError().text();
        return false;
    }

    // 清空并加载数据
    beginResetModel();
    m_alarms.clear();

    while (query.next())
    {
        AlarmRecord alarm;
        alarm.setId(query.value(0).toInt());
        alarm.setDeviceId(query.value(1).toString());
        alarm.setTimestamp(query.value(2).toDateTime());
        alarm.setAlarmType(AlarmRecord::stringToAlarmType(query.value(3).toString()));
        alarm.setAlarmLevel(AlarmRecord::stringToAlarmLevel(query.value(4).toString()));
        alarm.setParamName(query.value(5).toString());
        alarm.setParamValue(query.value(6).toDouble());
        alarm.setThreshold(query.value(7).toDouble());
        alarm.setDescription(query.value(8).toString());
        alarm.setAcknowledged(query.value(9).toBool());
        alarm.setAcknowledgedBy(query.value(10).toString());
        alarm.setAcknowledgedAt(query.value(11).toDateTime());

        m_alarms.append(alarm);
    }

    endResetModel();
    emit countChanged();
    emit unacknowledgedCountChanged();

    return true;
}

// 添加报警记录
bool AlarmModel::addAlarmRecord(const QString &deviceId,
                                const QString &alarmType,
                                const QString &alarmLevel,
                                const QString &paramName,
                                double paramValue,
                                double threshold,
                                const QString &description)
{
    AlarmRecord alarm;
    alarm.setDeviceId(deviceId);
    alarm.setTimestamp(QDateTime::currentDateTime());
    alarm.setAlarmType(AlarmRecord::stringToAlarmType(alarmType));
    alarm.setAlarmLevel(AlarmRecord::stringToAlarmLevel(alarmLevel));
    alarm.setParamName(paramName);
    alarm.setParamValue(paramValue);
    alarm.setThreshold(threshold);
    alarm.setDescription(description);

    // 保存到数据库
    if (!saveToDatabase(alarm))
    {
        return false;
    }

    // 添加到模型
    beginInsertRows(QModelIndex(), 0, 0);
    m_alarms.prepend(alarm);
    endInsertRows();

    emit countChanged();
    emit unacknowledgedCountChanged();
    emit alarmAdded(alarm.id());

    // 记录日志
    Logger::instance()->logOperation("add_alarm", deviceId,
                                     QString("添加报警: %1").arg(description));

    qInfo() << "AlarmModel: 添加报警 -" << deviceId << "-" << description;
    return true;
}

// 确认报警（根据索引）
bool AlarmModel::acknowledgeAlarm(int index, const QString &userName)
{
    if (index < 0 || index >= m_alarms.count())
    {
        qWarning() << "AlarmModel: 索引越界:" << index;
        return false;
    }

    AlarmRecord &alarm = m_alarms[index];
    int alarmId = alarm.id();

    // 更新数据库
    if (!updateAcknowledgedStatus(alarmId, userName))
    {
        return false;
    }

    // 更新模型
    alarm.setAcknowledged(true);
    alarm.setAcknowledgedBy(userName);
    alarm.setAcknowledgedAt(QDateTime::currentDateTime());

    QModelIndex modelIndex = createIndex(index, 0);
    emit dataChanged(modelIndex, modelIndex);
    emit unacknowledgedCountChanged();
    emit alarmAcknowledged(alarmId);

    // 记录日志
    Logger::instance()->logOperation("acknowledge_alarm", alarm.deviceId(),
                                     QString("确认报警: ID=%1").arg(alarmId), userName);

    qInfo() << "AlarmModel: 确认报警 - ID:" << alarmId;
    return true;
}

// 确认报警（根据ID）
bool AlarmModel::acknowledgeAlarmById(int alarmId, const QString &userName)
{
    for (int i = 0; i < m_alarms.count(); ++i)
    {
        if (m_alarms.at(i).id() == alarmId)
        {
            return acknowledgeAlarm(i, userName);
        }
    }

    qWarning() << "AlarmModel: 未找到报警ID:" << alarmId;
    return false;
}

// 确认所有报警
bool AlarmModel::acknowledgeAllAlarms(const QString &userName)
{
    int acknowledgedCount = 0;

    for (int i = 0; i < m_alarms.count(); ++i)
    {
        if (!m_alarms.at(i).isAcknowledged())
        {
            if (acknowledgeAlarm(i, userName))
            {
                acknowledgedCount++;
            }
        }
    }

    qInfo() << "AlarmModel: 批量确认报警，共" << acknowledgedCount << "条";
    return acknowledgedCount > 0;
}

// 获取报警记录
AlarmRecord AlarmModel::getAlarmRecord(int index) const
{
    if (index >= 0 && index < m_alarms.count())
    {
        return m_alarms.at(index);
    }
    return AlarmRecord();
}

// 删除报警记录（根据索引）
bool AlarmModel::removeAlarm(int index)
{
    if (index < 0 || index >= m_alarms.count())
    {
        qWarning() << "AlarmModel: 索引越界:" << index;
        return false;
    }

    const AlarmRecord &alarm = m_alarms.at(index);
    int alarmId = alarm.id();

    // 从数据库删除
    if (!deleteFromDatabase(alarmId))
    {
        return false;
    }

    // 从模型删除
    beginRemoveRows(QModelIndex(), index, index);
    m_alarms.removeAt(index);
    endRemoveRows();

    emit countChanged();
    emit unacknowledgedCountChanged();

    qInfo() << "AlarmModel: 删除报警 - ID:" << alarmId;
    return true;
}

// 删除报警记录（根据ID）
bool AlarmModel::removeAlarmById(int alarmId)
{
    for (int i = 0; i < m_alarms.count(); ++i)
    {
        if (m_alarms.at(i).id() == alarmId)
        {
            return removeAlarm(i);
        }
    }

    qWarning() << "AlarmModel: 未找到报警ID:" << alarmId;
    return false;
}

// 清空所有报警
bool AlarmModel::clearAllAlarms()
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    if (!query.exec("DELETE FROM alarm_records"))
    {
        qWarning() << "AlarmModel: 清空失败:" << query.lastError().text();
        return false;
    }

    beginResetModel();
    m_alarms.clear();
    endResetModel();

    emit countChanged();
    emit unacknowledgedCountChanged();

    Logger::instance()->logOperation("clear_alarms", "system", "清空所有报警记录");

    qInfo() << "AlarmModel: 清空所有报警记录";
    return true;
}

// 获取严重报警数量
int AlarmModel::getCriticalAlarmCount() const
{
    int count = 0;
    for (const AlarmRecord &alarm : m_alarms)
    {
        if (alarm.alarmLevel() == AlarmRecord::Critical)
            count++;
    }
    return count;
}

// 获取警告报警数量
int AlarmModel::getWarningAlarmCount() const
{
    int count = 0;
    for (const AlarmRecord &alarm : m_alarms)
    {
        if (alarm.alarmLevel() == AlarmRecord::Warning)
            count++;
    }
    return count;
}

// 获取信息报警数量
int AlarmModel::getInfoAlarmCount() const
{
    int count = 0;
    for (const AlarmRecord &alarm : m_alarms)
    {
        if (alarm.alarmLevel() == AlarmRecord::Info)
            count++;
    }
    return count;
}

// 清空过滤条件
void AlarmModel::clearFilters()
{
    m_deviceIdFilter.clear();
    m_levelFilter.clear();
    m_showOnlyUnacknowledged = false;

    emit deviceIdFilterChanged();
    emit levelFilterChanged();
    emit showOnlyUnacknowledgedChanged();

    qInfo() << "AlarmModel: 清空所有过滤条件";
}

// 保存报警记录到数据库
bool AlarmModel::saveToDatabase(const AlarmRecord &alarm)
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    query.prepare(R"(
        INSERT INTO alarm_records 
        (device_id, alarm_type, alarm_level, param_name, param_value, 
         threshold, description)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    )");

    query.addBindValue(alarm.deviceId());
    query.addBindValue(alarm.alarmTypeString());
    query.addBindValue(alarm.alarmLevelString());
    query.addBindValue(alarm.paramName());
    query.addBindValue(alarm.paramValue());
    query.addBindValue(alarm.threshold());
    query.addBindValue(alarm.description());

    if (!query.exec())
    {
        qWarning() << "AlarmModel: 保存失败:" << query.lastError().text();
        return false;
    }

    return true;
}

// 从数据库删除报警记录
bool AlarmModel::deleteFromDatabase(int alarmId)
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    query.prepare("DELETE FROM alarm_records WHERE id = ?");
    query.addBindValue(alarmId);

    if (!query.exec())
    {
        qWarning() << "AlarmModel: 删除失败:" << query.lastError().text();
        return false;
    }

    return true;
}

// 更新报警确认状态到数据库
bool AlarmModel::updateAcknowledgedStatus(int alarmId, const QString &userName)
{
    QSqlDatabase db = DatabaseService::instance()->database();
    QSqlQuery query(db);

    query.prepare(R"(
        UPDATE alarm_records 
        SET acknowledged = 1, 
            acknowledged_by = ?, 
            acknowledged_at = datetime('now', 'localtime')
        WHERE id = ?
    )");

    query.addBindValue(userName);
    query.addBindValue(alarmId);

    if (!query.exec())
    {
        qWarning() << "AlarmModel: 更新确认状态失败:" << query.lastError().text();
        return false;
    }

    return true;
}

// 构建 WHERE 子句
QString AlarmModel::buildWhereClause() const
{
    QStringList conditions;

    // 设备ID过滤
    if (!m_deviceIdFilter.isEmpty())
    {
        conditions.append(QString("device_id = '%1'").arg(m_deviceIdFilter));
    }

    // 报警级别过滤
    if (!m_levelFilter.isEmpty())
    {
        conditions.append(QString("alarm_level = '%1'").arg(m_levelFilter));
    }

    // 仅显示未确认报警
    if (m_showOnlyUnacknowledged)
    {
        conditions.append("acknowledged = 0");
    }

    // 如果没有条件，返回 "1=1"（始终为真）
    if (conditions.isEmpty())
    {
        return "1=1";
    }

    return conditions.join(" AND ");
}

// 应用过滤条件
QList<AlarmRecord> AlarmModel::applyFilters(const QList<AlarmRecord> &alarms) const
{
    QList<AlarmRecord> filtered;

    for (const AlarmRecord &alarm : alarms)
    {
        bool match = true;

        // 设备ID过滤
        if (!m_deviceIdFilter.isEmpty() && alarm.deviceId() != m_deviceIdFilter)
        {
            match = false;
        }

        // 报警级别过滤
        if (!m_levelFilter.isEmpty() && alarm.alarmLevelString() != m_levelFilter)
        {
            match = false;
        }

        // 仅显示未确认报警
        if (m_showOnlyUnacknowledged && alarm.isAcknowledged())
        {
            match = false;
        }

        if (match)
        {
            filtered.append(alarm);
        }
    }

    return filtered;
}
